//
//  VerifyViewController.m
//  lhcx
//
//  Created by 赵永杰 on 2017/5/9.
//  Copyright © 2017年 zhaoyongjie. All rights reserved.
//

#import "VerifyViewController.h"
#import "LHNetworking.h"
#import <JPush/JPUSHService.h>
#import <SMS_SDK/SMSSDK.h>

@interface VerifyViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconTop;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconWidth;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconHeight;

@property (weak, nonatomic) IBOutlet UILabel *mobileLabel;

/**
 倒计时按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *countBtn;

/**
 从新输入验证码
 */
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;

/**
 登陆
 */
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (weak, nonatomic) IBOutlet UITextField *tempTF;

@property (nonatomic, strong) UILabel *currentLabel;

@property (nonatomic, assign) NSInteger count;

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation VerifyViewController

#pragma mark - LifeCycle

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tempTF becomeFirstResponder];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"输入验证码";
    
    [self setupChildViews];
    
    [self addObserver];
}


#pragma mark - Public

#pragma mark - Private

- (void)setupChildViews {
    for (int i = 1; i < 5; i++) {
        UILabel *label = [self.view viewWithTag:1000+i];
        label.layer.borderWidth = 1;
        label.layer.cornerRadius = 2;
        label.layer.borderColor = HLHexColor(@"bababa").CGColor;
        label.layer.masksToBounds = YES;
    }
    self.mobileLabel.text = self.mobile;
    [self.countBtn setTitle:@"60S后重发" forState:UIControlStateNormal];
    self.countBtn.enabled = NO;
    [self startCountDown];
}

// 开始倒计时
- (void)startCountDown {
    self.count = 60;
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

// 计时器的执行方法
- (void)changeCountDown {
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if (self.count > 0) {
            NSString *title = [NSString stringWithFormat:@"%ldS后获取验证码",self.count];
            self.countBtn.enabled = NO;
            self.countBtn.titleLabel.text = title;
            [self.countBtn setTitle:title forState:UIControlStateNormal];
            [self.countBtn setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
        }else{
            [self.timer invalidate];
            self.timer = nil;
            NSString *title = @"点击获取验证码";
            self.countBtn.enabled = YES;
            self.countBtn.titleLabel.text = title;
            [self.countBtn setTitle:title forState:UIControlStateNormal];
            [self.countBtn setTitleColor:ORANGCOLOR forState:UIControlStateNormal];

        }
    });
    self.count--;

    
}

- (void)updateViewConstraints {
    [super updateViewConstraints];
    
    if (kScreenW > 320) {
        self.iconTop.constant = kScreenH * 0.14;
        self.iconWidth.constant = kScreenW * 0.3;
        self.iconHeight.constant = kScreenW * 0.3 * 187/130;
    }
}

- (void)addObserver {
    [self.tempTF addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
}

- (void)textFieldChanged:(UITextField *)textField {
    NSString *text = textField.text;
    if (text.length > 4) {
        // 4位验证码
        textField.text = [text substringToIndex:4];
        return;
    }
    
    for (int i = 0; i < 4; i++) {
        UILabel *label = [self.view viewWithTag:1001 + i];
        if (i < text.length) {
            label.text = [textField.text substringWithRange:NSMakeRange(i, 1)];
        }else{
            label.text = @"";
        }
    }
    
    if (text.length == 4) {
        [self.tempTF resignFirstResponder];
    }
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.text.length != 4) {
        self.loginBtn.backgroundColor = GRAYCOLOR;
        self.loginBtn.userInteractionEnabled = NO;
    }else{
        self.loginBtn.backgroundColor = ORANGCOLOR;
        self.loginBtn.userInteractionEnabled = YES;
    }
}

// 倒计时
- (IBAction)countDownAction:(UIButton *)sender {
    
//    LHPC_WEAK_SELF;
    [HLProgressHUD showHUDWithStyle:HLProgressHUDStyleLoading status:@"正在发送验证码"];
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.mobile zone:@"86" result:^(NSError *error) {
//        LHPC_STRONG_SELF;
        [HLProgressHUD dismissHUD];
        if (!error) {
            NSLog(@"获取验证码成功");
            [HLProgressHUD showHUDWithStyle:HLProgressHUDStyleSuccess status:@"发送验证码成功"];
        } else {
            [HLProgressHUD showHUDWithStyle:HLProgressHUDStyleError status:[NSString stringWithFormat:@"%@",error]];
            NSLog(@"错误信息：%@",error);
        };
    }];
}

// 从新输入
- (IBAction)reInputAction:(UIButton *)sender {
    [self.tempTF becomeFirstResponder];
}

// 登陆
- (IBAction)loginAction:(UIButton *)sender {
    
    if (self.isChangePhone) {
        
    }else{
        [self __loginAction];
    }
    
}


- (void)__loginAction {
    [HLProgressHUD showHUDWithStyle:HLProgressHUDStyleLoading status:@"正在登录"];
    LHPC_WEAK_SELF;
    [[LHNetworking shared] POSTNoToken:LHSetRequestAPI(LHSepUserLogin) parameters:@{@"mobile" : self.mobile, @"code" : self.tempTF.text} success:^(NSURLSessionDataTask *task, id responseObject) {
        LHPC_STRONG_SELF;
        
        if (responseObject) {
            
            [HLNoteCenter postNotificationName:LHChangeRootVCToHomeVC object:nil];
            
            NSDictionary * resultDic = responseObject[@"data"];
            
            LHSetUserPhone(resultDic[@"phone"]);
            LHSetUserToken(resultDic[@"token"]);
            LHSetUserID(resultDic[@"userId"]);
            
            
            [strongSelf.navigationController popViewControllerAnimated:NO];
            
            [HLProgressHUD showHUDWithStyle:HLProgressHUDStyleSuccess status:@"登陆成功"];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [HLProgressHUD showHudTipStr:LHNetWorkErrorMessage];
    }];
}


#pragma mark - UITableViewDelegate

#pragma mark - Getter

- (NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(changeCountDown) userInfo:nil repeats:YES];
    }
    return _timer;
}

#pragma mark - Setter

@end
